<?php

namespace Modules\Order\Http\Controllers\API;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Modules\Order\Services\OrderService;
use Modules\Order\Services\PaymentService;
use Modules\Order\Services\DeliveryService;
use Modules\Order\Services\WechatPaymentService;

class OrderController extends Controller
{
    // 1 待付款,2 待发货,3 待收货 ,4 待评价 （status 不传则为全部订单）
    public function list(Request $request, OrderService $sOrder)
    {
        // 1 待付款 < STATUS_PAIED 2
        // 2 待发货 < STATUS_DELIVERED  3
        // 3 待收货 < STATUS_RECEIVED 4
        // 4 待评价 （status 不传则为全部订单）
        // $state = 0;
        // swtich($request->status) {
        //     case 1: $state = Order:
        // }
        return $sOrder->getOrderByStatus($request->status);
    }

    // 更新商品信息和价格
    public function check(Request $request, OrderService $sOrder, PaymentService $sPayment)
    {
        $goods = $sOrder->refresh($request->goods);
        $fee = $sPayment->fee($goods);

        return compact('goods', 'fee');
    }

    // 提交订单
    public function commit(Request $request, OrderService $sOrder, DeliveryService $sDelivery, PaymentService $sPayment)
    {
        $goods = $sOrder->refresh($request->goods);

        DB::beginTransaction();
        try {
            $order = $sOrder->create($request->merchantId, $request->channel, $request->postscript, $goods);
            $sPayment->create($order, $goods);
            $sDelivery->create($order, $request->delivery);
            // 支付
            $sign = $sPayment->pay($order);

            DB::commit();
        } catch (InvalidConfigException $e) {
            DB::rollBack();
            return null;
        }

        return compact('order', 'sign');
    }

    // 支付成功后的回调
    public function notifyForWechatPayment(WechatPaymentService $sWechatPayment)
    {
        return $sWechatPayment->payNotifyHander();
    }
}
